// 救援队伍
import Util from '@/gis/Util';
import any = jasmine.any;

const componentBase = (G as any).base.ComponentBase;
const component = componentBase.extend({
    // 属性
    options: {
        highLightId: 'rescueteam_sjts', // 高亮id
        popupId: 'popup_rescueteam_sjts', // 弹窗唯一标识
        popupEventName: 'popup', // 详情框事件名
        featureType: 'rescueteam_sjts', // 图层标识
    },
    // 初始化
    initialize(options: any) {
        componentBase.prototype.initialize.call(this, options);
        const map = this.map;
        const handler = this;
        /*this.mousedownEvent = this.mousedownFunc.bind(this);
         this.mouseupEvent = this.mouseupFunc.bind(this);
         this.mousemoveEvent = this.mousemoveFunc.bind(this);*/
        map.listen('mousemove', this.mousemoveFunc, handler);
        map.listen('mouseup', this.mouseupFunc, handler);
        map.listen('mousedown', this.mousedownFunc, handler);
    },
    //  销毁
    destroy() {
        componentBase.prototype.destroy.call(this);
    },

    load() {
        componentBase.prototype.load.call(this);
        this._load();
    },

    /**
     *  列表中选中
     * @param id 对象id
     */
        select(id: any): void {
        this.save();// 置空之前编辑操作
        this.location(id);
        this.modifyFlag = true;
        /*if (!!this.dataList) {
         for (let i = 0, len = this.dataList.length; i < len; ++i) {
         const item = this.dataList[i];
         if (item.teamid === id) {
         this.selectedItem = item;
         break;
         }
         }
         if (!!this.selectedItem) {
         const coordinate: any = [this.selectedItem.lon, this.selectedItem.lat];
         const type = this.selectedItem.areaflag;
         this.map.setCenter({x: coordinate[0], y: coordinate[1]});
         this._addHighlightEx(type, coordinate);
         }

         this.closePopup();
         }*/
    },

    /**
     *  列表中定位
     * @param id 对象id
     */
        location(id: any): void {
        this.save();// 置空之前编辑操作
        if (!!this.dataList) {
            for (let i = 0, len = this.dataList.length; i < len; ++i) {
                const item = this.dataList[i];
                if (item.teamid === id) {
                    this.selectedItem = item;
                    break;
                }
            }
            if (!!this.selectedItem) {
                const coordinate: any = [this.selectedItem.lon, this.selectedItem.lat];
                const type = this.selectedItem.areaflag;
                this.map.setCenter({x: coordinate[0], y: coordinate[1]});
                this._addHighlightEx(type, coordinate);
            }

            this.closePopup();
        }
    },

    //保存更改
    save() {
        this._removehighlight();
        this.selectedItem = null;
        this.modifyFlag = false;
    },

    getModifyItem(): any {
        return this.selectedItem
    },

    mousedownFunc(parameters: any) {
        this.mousedownFlag = true;
        if (!!this.modifyFlag) {
            const layer: any = this.options.simpleRenderMgr.getLayer(this.options.featureType);
            const groupLayers = layer.groupLayers;
            let graphic: any = null;
            for (let i = 0; i < groupLayers.length; ++i) {
                const lyr = groupLayers[i];
                graphic = lyr.hitTest(parameters.screenX, parameters.screenY);
                if (!!graphic) {
                    break;
                }
            }
            this.hitTest = !!graphic && graphic.feature.objectId === this.selectedItem.teamid ? true : false;
            if (!!this.hitTest) {
                this.map.stopDragPan();
            } else {
                this.map.resumeDragPan();
            }
        }
    },

    mouseupFunc(parameters: any) {
        this.mousedownFlag = false;
        this.map.resumeDragPan();
    },

    mousemoveFunc(parameters: any) {
        if (!!this.mousedownFlag && !!this.selectedItem && !!this.modifyFlag && this.hitTest) {
            const mapX = parameters.mapX;
            const mapY = parameters.mapY;
            this.selectedItem.lon = mapX;
            this.selectedItem.lat = mapY;
            const opts = {
                featureType: 'rescueteam_sjts',
                list: [this.selectedItem]
            }
            this.options.simpleRenderMgr.update(opts);
        }
    },

    //更新坐标
    async update() {
        this.modifyFlag = true;
        /*const list1: any = await this.options.service.list();
         const opts = {
         featureType: 'rescueteam_sjts',
         list: list1
         }
         this.options.simpleRenderMgr.update(opts);*/
    },

    addListeners() {
        // 添加事件监听，load调用时父类触发
    },

    unload() {
        this.options.simpleRenderMgr.remove(this.options.featureType);
        this.closePopup();
        this._removehighlight();
        if (!!this.myChart) {
            this.myChart.unbind();
            this.myChart = null;
        }
        componentBase.prototype.unload.call(this);
    },

    removeListeners() {
        // 移除事件监听，unload调用时父类触发
    },

    closePopup() {
        this.options.popupManager.remove(this.options.popupId);
    },

    async _load() {
        this.dataList = await this.options.service.list();
        this.addPoints(this.dataList);
    },

    addPoints(list: any) {
        const opts: any = {};
        opts.featureType = this.options.featureType;
        opts.idField = 'teamid'; // 数据唯一标识的属性
        opts.list = this.dataList; // 数据列表
        opts.type = 1; // 使用feature渲染
        opts.geometryBuilder = new this.options.PointGeometryBuilder({
            geometryField: ['lon', 'lat'],
        });
        const symbolObjs: any = {
            0: {
                type: 'PictureMarkerSymbol',
                options: {
                    width: 34,
                    height: 46,
                    offsetX: 17,
                    offsetY: 46,
                    opacity: '1',
                    rotation: '0',
                    source: this.options.symbolConfig.icons.localTeam_icon,
                },
            },
            1: {
                type: 'PictureMarkerSymbol',
                options: {
                    width: 34,
                    height: 46,
                    offsetX: 17,
                    offsetY: 46,
                    opacity: '1',
                    rotation: '0',
                    source: this.options.symbolConfig.icons.localTeam_icon,
                },
            },
            2: {
                type: 'PictureMarkerSymbol',
                options: {
                    width: 34,
                    height: 46,
                    offsetX: 17,
                    offsetY: 46,
                    opacity: '1',
                    rotation: '0',
                    source: this.options.symbolConfig.icons.aidTeam_icon,
                },
            },
            3: {
                type: 'PictureMarkerSymbol',
                options: {
                    width: 34,
                    height: 46,
                    offsetX: 17,
                    offsetY: 46,
                    opacity: '1',
                    rotation: '0',
                    source: this.options.symbolConfig.icons.armyTeam_icon,
                },
            }
        };
        this.highlightSymbolObjs = {
            0: {
                type: 'PictureMarkerSymbol',
                options: {
                    width: 60,
                    height: 66,
                    offsetX: 30,
                    offsetY: 66,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons.localTeam_HightLight_icon,
                },
            },
            1: {
                type: 'PictureMarkerSymbol',
                options: {
                    width: 60,
                    height: 66,
                    offsetX: 30,
                    offsetY: 66,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons.localTeam_HightLight_icon,
                },
            },
            2: {
                type: 'PictureMarkerSymbol',
                options: {
                    width: 60,
                    height: 66,
                    offsetX: 30,
                    offsetY: 66,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons.aidTeam_HightLight_icon,
                },
            },
            3: {
                type: 'PictureMarkerSymbol',
                options: {
                    width: 60,
                    height: 66,
                    offsetX: 30,
                    offsetY: 66,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons.armyTeam_HightLight_icon,
                },
            }
        };
        const SymbolBuilder = (G as any).utils.SymbolBuilder.extend({
            build: (data: any) => {
                const type = data.areaflag;
                return G.utils.RenderUtil.object2Symbol(symbolObjs[type]);
            },
        });
        opts.symbolBuilder = new SymbolBuilder(),
            opts.listeners = {
                click: (event: any) => {
                    this._removehighlight();
                    if (!this.modifyFlag) {
                        const element: any = event[0].element;
                        this.closePopup();
                        /*const coordinate: any = [element.geometry.x, element.geometry.y];
                         const type = element.attributeSet.find('type').value;*/
                        this._addHighlight(element);
                        this.options.popupManager.addSimple({
                            id: this.options.popupId,
                            anchor: [element.geometry.x, element.geometry.y],
                            className: 'demo-tooltip',
                        }).then((content: any) => {
                            this.fire(this.options.popupEventName, {
                                data: Util.attributeSet2Object(element.attributeSet),
                                containerId: content.containerId,
                                type: 'demo',
                            });
                        });
                    }
                },
            };
        this.options.simpleRenderMgr.add(opts);
        this._fit();
    },

    addFlyRoute(list: any) {
        const data = createGeoJson(list);
        const source1 = new gv.source.GeoJsonSource(data);
        const myChart = new gv.chart.RoadChart(source1,
            {
                fieldName: {
                    id: 'id',
                    to: 'to',
                    icon: 'icon',
                    type: 'type',
                },
                type: "solid",
                pointStyle: {
                    symbolSize: 20,
                    fillStyle: '#0ff',
                    label: {
                        show: false,
                        // offset:[-15,0],
                        fontSize: '15px',
                        fillStyle: '#0ff',
                    },
                },
                legend: {
                    show: false
                }
            });
        this.myChart = myChart;
        myChart.bind(this.map, gv.chart.MapType.TSMap);
        myChart.render();
        this._flyFit(data);
        myChart.on('click', function (val: any) {
            console.log(val);
        });
        myChart.on('mouseover', function (val: any) {
            console.log(val);
        });
        myChart.on('mouseout', function (val: any) {
            console.log(val);
        });

        function createGeoJson(dataList: any) {
            const geoJson: any = {
                type: 'FeatureCollection',
                crs: {
                    type: 'name',
                    properties: {
                        name: 'urn:ogc:def:crs:OGC:1.3:CRS84',
                    },
                },
                features: [],
            };
            for (let i = 0; i < dataList.length; i++) {
                const item = dataList[i];
                geoJson.features.push({
                    type: 'Feature',
                    properties: {
                        id: item.lon.toFixed(4) + item.lat.toFixed(4),
                        to: item.lon.toFixed(4) + item.lat.toFixed(4),
                        type: 0,
                        icon: 'circle',
                    },
                    geometry: {
                        type: 'Point',
                        coordinates: [parseFloat(item.lon.toFixed(4)), parseFloat(item.lat.toFixed(4))],
                    },
                });
                geoJson.features.push({
                    type: 'Feature',
                    properties: {
                        id: item.hospsource,
                        to: item.lon.toFixed(4) + item.lat.toFixed(4),
                        type: 0,
                        icon: 'circle',
                    },
                    geometry: {
                        type: 'Point',
                        coordinates: [parseFloat(item.longitude.toFixed(4)), parseFloat(item.latitude.toFixed(4))],
                    },
                });
            }
            return geoJson;
        }
    },

    showTeam(num: number, dataList: any) {
        this.unload();
        this._showTeam(num, dataList);
    },

    _showTeam(num: number, dataList: any) {
        //this.dataList = await this.options.service.findByType(num);
        this.dataList = dataList;
        if (num * 1 === 1 || num * 1 === 0) {
            this.addPoints(this.dataList);
        } else {
            this.addFlyRoute(this.dataList);
        }
    },

    // 飞行路线调整视野
    _flyFit(geojson: any) {
        const gFeatureCollection = g2.sfs.GFeatureFormatter.fromGeoJson(geojson, 4326);
        const envelope = new g2.sfs.Envelope({spatialReference: 4326});
        for (let i = 0, len = gFeatureCollection.size(); i < len; i++) {
            const feature = gFeatureCollection.get(i);
            const geometry = feature.getGeometry();
            envelope.union(geometry.envelope());
        }
        this.map.pan(envelope, new Array(4).fill(100));
    },

    // 调整视野
    _fit() {
        const layer: any = this.options.simpleRenderMgr.getLayer(this.options.featureType);
        const extent: any = G.utils.LayerUtil.getLayerExtent(layer);
        this.map.pan(extent, new Array(4).fill(100));
    },

    _addHighlightEx(type: any, coordinate: number[]) {
        const symbolObj: any = this.highlightSymbolObjs[type];
        const options = {
            data: {
                type: 'wkt',
                geom: 'POINT(' + coordinate[0] + ' ' + coordinate[1] + ')',
            },
            style: symbolObj,
            // 不闪烁
            blink: {
                enable: true,
            },
        };
        this.options.featureHighlight.addHighlight(this.options.highLightId, options);
    },

    // 添加高亮
    _addHighlight(element: any) {
        const coordinate: any = [element.geometry.x, element.geometry.y];
        const type = element.attributeSet.find('areaflag').value;
        const symbolObj: any = this.highlightSymbolObjs[type];
        const options = {
            data: {
                type: 'wkt',
                geom: 'POINT(' + coordinate[0] + ' ' + coordinate[1] + ')',
            },
            style: symbolObj,
            // 不闪烁
            blink: {
                enable: false,
            },
        };
        this.options.featureHighlight.addHighlight(this.options.highLightId, options);
    },

    // 移除高亮
    _removehighlight() {
        this.options.featureHighlight.removeHighlight(this.options.highLightId);
    },
});

export default component;

































